<template>
  <div class="modal">
    <el-dialog
      v-model="dialogVisible"
      :title="isNewRef ? '新建部门' : '编辑部门'"
      width="50%"
      center
    >
      <div class="form">
        <el-form size="large" :model="formData" label-width="100px">
          <el-form-item label="部门名：" prop="name">
            <el-input
              placeholder="请输入部门名"
              v-model="formData.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门领导：" prop="leader">
            <el-input
              placeholder="请输入部门领导"
              v-model="formData.leader"
            ></el-input>
          </el-form-item>

          <el-form-item label="选择部门：" prop="parentId">
            <el-select
              style="width: 100%"
              placeholder="请选择部门"
              v-model="formData.parentId"
            >
              <template v-for="item in entireDepartments" :key="item.id">
                <el-option :label="item.name" :value="item.id"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="btnOk">确定</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            取消
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import useMainStore from '@/store/main/main'
import useSystemStore from '@/store/main/system/system'
import { storeToRefs } from 'pinia'
import { reactive, ref } from 'vue'

const dialogVisible = ref(false)
// 表单数据
const formData = reactive<any>({
  name: '',
  leader: '',
  parentId: ''
})
// 是否显示密码框 新建的时候显示
let isNewRef = ref(true)
let editData = ref()
//所有部门和角色数据
const mainStore = useMainStore()
const { entireDepartments } = storeToRefs(mainStore)
// 修改显示的方法
function setDialogVisible(isNew: boolean, itemData?: any) {
  isNewRef.value = isNew
  dialogVisible.value = true
  //是编辑   新建和编辑使用同一个对话框，所以要做区分
  if (!isNew && itemData) {
    // 编辑
    // formData = itemData
    for (const key in formData) {
      formData[key] = itemData[key]
    }
    editData.value = itemData
  } else {
    //新建 初始化数据都为空
    for (const key in formData) {
      formData[key] = ''
    }
    editData.value = null
  }
}

// 确定
function btnOk() {
  if (isNewRef.value) {
    // 传递数据，创建用户。网络请求
    // console.log('新建用户')
    const systemStore = useSystemStore()
    console.log(formData)

    systemStore.newPageDataAction('department', formData)
    // 隐藏
    dialogVisible.value = false
  } else {
    // 编辑用户
    // console.log('编辑用户')
    const systemStore = useSystemStore()
    systemStore.editPageDataAction('department', editData.value.id, formData)
    dialogVisible.value = false
  }
}
// 导出属性 点击新建用户 弹出对话框
// defineExpose({ dialogVisible })
// 暴露属性或者方法
defineExpose({ setDialogVisible })
</script>
<style lang="less" scoped>
.modal {
  color: red;
}
</style>
